import { setUpload, imgUrl } from "../../api/http.js";
import { Toast } from "vant";
//压缩图片为Base64路径格式
const Base64 = (img) => {
  let originWidth = img.width,
    originHeight = img.height,
    maxWidth = 1000,
    quality = 0.5, // 压缩质量
    canvas = document.createElement("canvas"),
    drawer = canvas.getContext("2d");
  canvas.width = maxWidth;
  canvas.height = (originHeight / originWidth) * maxWidth;
  drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
  let base64 = canvas.toDataURL("image/jpeg", quality); // 压缩后的base64图片
  let file = dataURLtoFile(base64, Date.parse(Date()) + ".jpg");
  file = {
    content: base64,
    file: file,
  };
  return file;
};
//把base64转file 二进制流
const dataURLtoFile = (dataurl, filename) => {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime,
  });
};

const uploaFile = async (file) => {
  let param = new FormData();
  param.append("file", file.file);
  const data = await setUpload(param);
  if (data.code !== 200) return Toast.fail("图片上传失败");
  return imgUrl + data.data;
};

const getImgByteSize = (file, size) => {
  // 获取base64图片byte大小
  let fileSize;
  const equalIndex = file.indexOf("="); // 获取=号下标
  if (equalIndex > 0) {
    const str = file.substring(0, equalIndex); // 去除=号
    const strLength = str.length;
    const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
    fileSize = Math.floor(fileLength); // 向下取整
  } else {
    const strLength = file.length;
    const fileLength = strLength - (strLength / 8) * 2;
    fileSize = Math.floor(fileLength); // 向下取整
  }
  console.log(fileSize, size * 1024 * 1024);
  return fileSize > size * 1024 * 1024;
};

//上传时调用uploadImg即可
export default function (file) {
  console.log("函数中---", file);
  return new Promise((resolve) => {
    const size = getImgByteSize(file.content, 4);
    if (!size) return resolve(uploaFile(file));
    let img = new Image();
    img.src = file.content;
    img.onload = () => {
      let file = Base64(img);
      resolve(uploaFile(file));
    };
  });
}
